package com.lz.sports.vm

import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import com.lz.helper.idcard.IDCardInfo
import com.lz.library.base.BaseModel
import com.lz.library.base.BaseViewModel
import com.lz.sports.R
import com.lz.sports.bean.ExamSignIn
import com.lz.sports.bean.Examinee
import com.lz.sports.core.ProjectManager
import com.lz.sports.db.ExamineeDatabase
import com.lz.sports.ui.checkmodel.FeatureResult
import com.lz.sports.utils.ToastUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext

//校验
class SignInViewModel : BaseViewModel<BaseModel>() {

    private val examPlanId = ProjectManager.examPlanId()
    //考区ID
    private val examAreaId = ProjectManager.examAreaId()
    //考点ID
    private val examSiteId = ProjectManager.examSiteId()

    val examinee = MutableLiveData<Examinee>()
    //是否正在查找
    var isFinding = false

    //通过身份证查询考生
    fun findExaminee(idCardInfo: IDCardInfo) {
        launch {
            isFinding = true
            val findJob = async(Dispatchers.Default) {
                val examinee = ExamineeDatabase.get().findExamineeByIdCard(examPlanId, examAreaId, examSiteId, idCardInfo.num)
                if (examinee != null) {
                    ExamineeDatabase.get().signIn(ExamSignIn(examinee, idCardInfo))
                }
                examinee
            }
            examinee.value = findJob.await()
            isFinding = false
        }
    }

    //人脸识别时的查找学生
    fun findIdentifyExaminee(idCardInfo: IDCardInfo): Examinee? {
        val examinee = ExamineeDatabase.get().findExamineeByIdCard(examPlanId, examAreaId, examSiteId, idCardInfo.num)
        if (examinee == null) {
            launch {
                ToastUtils.showMyToast(R.string.inspect_in_none, Toast.LENGTH_SHORT)
            }
        }
        return examinee
    }

    //保存考生信息
    fun saveExaminee(result: FeatureResult) {
        launch {
            withContext(Dispatchers.Default) {
                ExamineeDatabase.get().signIn(ExamSignIn(result))
            }
        }
    }
}